var express = require('express');
var router = express.Router();
const Bizdef = require('../models/Bizdef');
const Bizrela = require('../models/Bizrela');
const Bizrelainst = require('../models/Bizrelainst');
const RelationType = require('../models/RelationType');
var formidable = require('formidable');
var fs = require('fs');
const mineType = require("mime-types");
var tools = require('../utils/tools')

/**
 * @swagger
 *
 * /cmdb/bizrelas/page:
 *   get:
 *     tags:
 *       - 业务关系模型管理
 *     summary: 分页查询关系
 *     description: 支持标准方式查询。$_foo=bar
 *     responses:
 *       200:
 *         description: 返回标准分页结构
 */
router.get('/page', function (req, res, next) {
  Bizrela.page(tools.queryResolver(req.query), req.query.page, req.query.size, result => {
    return res.json({ status: 'success', data: result.docs, pageable: result.pageable })
  })
});

/**
 * @swagger
 *
 * /cmdb/bizrelas/list:
 *   get:
 *     tags:
 *       - 业务关系模型管理
 *     summary: 查询所有关系
 *     description: 查询所有关系
 *     responses:
 *       200:
 *         description: 查询所有关系
 */
router.get('/list', async function (req, res, next) {
  var docs = await Bizrela.find(tools.queryResolver(req.query))
    .populate('type')
    .populate('src')
    .populate('dest')
  return res.json({ status: 'success', data: docs })
});

/**
 * @swagger
 * /cmdb/bizrelas/{id}:
 *   get:
 *     tags:
 *       - 业务关系模型管理
 *     summary: 业务关系模型详情
 *     description: 业务关系模型详情
 *     parameters:
 *       - name: id
 *         description: ID或编码
 *         in: path
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: status/data结构
 */
router.get('/:id', function (req, res, next) {
  Bizrela.findOne({ _id: req.params.id })
    .populate('type')
    .populate('src')
    .populate('dest')
    .exec((err, doc) => {
      if (err) res.json({ status: 'failure' });
      res.json({ status: 'success', data: doc })
    })
});

/**
 * @swagger
 *
 * /cmdb/bizrelas/{id}:
 *   put:
 *     tags:
 *       - 业务关系模型管理
 *     summary: 修改关联模型
 *     description: 修改关联模型。约束有效值onetoone, onetomany, manytomany, manytoone
 *     parameters:
 *       - name: id
 *         description: ID或编码
 *         in: path
 *         required: true
 *         type: string
 *       - name: type
 *         description: 关联类型ID
 *         in: formData
 *         required: true
 *         type: string
 *       - name: src
 *         description: 源业务模型ID
 *         in: formData
 *         required: true
 *         type: string
 *       - name: dest
 *         description: 目标业务模型ID
 *         in: formData
 *         required: true
 *         type: string
 *       - name: restrain
 *         description: 约束
 *         in: formData
 *         required: true
 *         type: string
 *       - name: desc
 *         description: 描述
 *         in: formData
 *         required: false
 *         type: string
 *       - name: attrs
 *         description: 属性定义
 *         in: formData
 *         required: false
 *         type: arrays
 *     responses:
 *       200:
 *         description: status/data结构
 */
router.put('/:id', async function (req, res, next) {
  var { type, src, dest, desc, restrain, attrs } = req.body

  var count = await Bizrelainst.count({ rela: req.params.id })
  if (count > 0) {
    return tools.handleError(res, '关系实例已存在，无法完成更新');
  }
  var typeInst = await RelationType.findById(tools.isObject(type) ? type._id : type)
  var srcInst = await Bizdef.findById(tools.isObject(src) ? src._id : src)
  var destInst = await Bizdef.findById(tools.isObject(dest) ? dest._id : dest)

  if (!typeInst || !srcInst || !destInst) {
    return tools.handleError(res, '关系类型，源业务模型或目标业务模型不存在，无法完成更新');
  }

  var data = {
    type: typeInst._id,
    src: srcInst._id,
    dest: destInst._id,
    attrs,
    restrain,
    desc
  }

  Bizrela.findByIdAndUpdate(req.params.id, { $set: data }, { new: false }, function (err, doc) {
    if (err) return tools.handleError(res, err);
    res.json({ status: 'success', data: doc })
  });
});

/**
 * @swagger
 *
 * /cmdb/bizrelas/{id}:
 *   delete:
 *     tags:
 *       - 业务关系模型管理
 *     summary: 删除业务模型关系
 *     description: 删除业务模型关系
 *     parameters:
 *       - name: id
 *         description: ID
 *         in: path
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: 存在关联关系、存在实例类，status=failure
 */
router.delete('/:id', function (req, res, next) {
  Bizrela.findByIdAndDelete(req.params.id, function (err, doc) {
    if (err) return tools.handleError(res, err);
    res.json({ status: 'success', data: doc })
  });
});

module.exports = router;
